package com.gitee.faster.webdav.common.helper;

import cn.hutool.core.text.CharSequenceUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.gitee.faster.webdav.exception.ReadException;
import com.gitee.faster.webdav.exception.WriteException;

import java.util.List;
import java.util.Map;

/**
 * @author hongda.li
 */
public final class JsonHelper {

    private static final TypeReference<Map<String, Object>> MAP_TYPE_REFERENCE = new TypeReference<>() {
    };

    private JsonHelper() {
    }

    public static String toJson(Object object) {
        try {
            return JSON.toJSONString(object);
        } catch (Exception e) {
            throw new WriteException("写入JSON数据出现异常", e);
        }
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        if (CharSequenceUtil.isEmpty(json)) {
            return null;
        }
        try {
            return JSON.parseObject(json, clazz);
        } catch (Exception e) {
            throw new ReadException("读取JSON数据出现异常", e);
        }
    }

    public static <T> List<T> fromJsonList(String json, final Class<T> clazz) {
        if (CharSequenceUtil.isEmpty(json)) {
            return null;
        }
        try {
            return JSON.parseArray(json, clazz);
        } catch (Exception e) {
            throw new ReadException("读取JSON数据出现异常", e);
        }
    }

    public static <T> T fromJson(String json, TypeReference<T> typeReference) {
        if (CharSequenceUtil.isEmpty(json)) {
            return null;
        }
        try {
            return JSON.parseObject(json, typeReference);
        } catch (Exception e) {
            throw new ReadException("读取JSON数据出现异常", e);
        }
    }

    public static Map<String, Object> fromJsonMap(String json) {
        return fromJson(json, MAP_TYPE_REFERENCE);
    }
}
